export interface LoginRequest {
  userName: string
  userPass: string
}

export interface LoginResponse {
  userId: number
  userName: string
  userPass: null
  userNickname: string
  roleId: number
  roleName: string
  createTime: string | null
  status: boolean
  token: string
  permissions: Permission[]
}

export interface Permission {
  permissionId: number
  permissionName: string
  permissionUrl: string
  createTime: string
  status: boolean
  isDel: boolean
}

export interface ApiResponse<T = any> {
  code: number
  message: string
  data: T
}

export interface UserInfo {
  userId: number
  userName: string
  userNickname: string
  roleId: number
  roleName: string
  token: string
  permissions: Permission[]
  avatar?: string
  phone?: string
  medicalCardNo?: string
  balance?: number
  createTime?: string
}

export interface Patient {
  patientId: number
  relationship: string
  name: string
  idCardType: string
  idCardNum: string
  medicalCard: string
  phone: string
  address: string
  isDefault: boolean
  isDel: boolean
}

export interface PatientForm {
  relationship: string
  name: string
  idCardType: string
  idCardNum: string
  medicalCard: string
  phone: string
  address: string
  isDefault: boolean
}

export interface VisitRecord {
  visitrecordId: number
  patientId: number
  name: string
  idCardNum: string
  medicalCard: string
  phone: string
  doctorId: number
  doctorName: string
  departmentId: number
  departmentName: string
  visitTime: string
  totalfee: number
  createdTime: string
}

export interface PrescriptionMedicine {
  prescriptionMedicineId: number
  visitrecordId: number
  medicineName: string
  unitprice: number
  quantity: number
}

export interface Notice {
  id: number
  title: string
  content: string
  type: string
  department?: string
  startTime?: string
  endTime?: string
  createTime: string
}

export interface Service {
  id: number
  name: string
  subtitle?: string
  icon: string
  color?: string
  url?: string
}

export interface Appointment {
  id: number
  appointmentNo: string
  departmentName: string
  doctorName: string
  appointmentDate: string
  timeSlot: string
  status: string
  symptoms: string
  createTime: string
}

export interface RechargeRecord {
  id: number
  orderId: string
  amount: number
  status: string
  paymentMethod: string
  createTime: string
  completeTime?: string
}

export interface PaymentRecord {
  id: number
  orderId: string
  billNo: string
  type: string
  amount: number
  status: string
  paymentMethod: string
  createTime: string
  completeTime?: string
}

export interface Inpatient {
  id: number
  name: string
  idCard: string
  phone: string
  relationship: string
  admissionNo: string
  ward: string
  bedNo: string
  admissionDate: string
  status: string
}

export interface MedicalReport {
  id: number
  reportNo: string
  type: string
  title: string
  department: string
  doctor: string
  status: string
  createTime: string
  completeTime?: string
}

export interface Feedback {
  id: number
  type: string
  title: string
  content: string
  contact: string
  images?: string[]
  status: string
  createTime: string
}

// 预约挂号记录相关接口
export interface AppointmentRecord {
  appointmentId: number
  attending: string
  doctorAddress: string
  department: string
  attendingName: string
  doctorName: string
  registTypeId: number
  outpatientTime: string
  waitingTime: string
  cost: number
  appointmentTime: string
  medicalstate: boolean
  reason?: string
  cancelTime?: string
  desc?: string
  registerName: string
  patientId: number
  relationship: string
  name: string
  idCardType: string
  idCardNum: string
  medicalCard: string
  phone: string
  departmentId: number
  departmentName: string
}

class SmartYLAPI {
  private readBaseURL: string
  private writeBaseURL: string
  private token: string

  constructor(readBaseURL: string = '', writeBaseURL: string = '', token: string = '') {
    this.readBaseURL = readBaseURL || 'http://localhost:5103'
    this.writeBaseURL = writeBaseURL || 'http://localhost:5250'
    this.token = token
  }

  // 设置认证Token
  setToken(token: string) {
    this.token = token
  }

  // 基础请求方法
  private async request<T>(endpoint: string, options: RequestInit = {}, useWriteAPI: boolean = false): Promise<ApiResponse<T>> {
    const baseURL = useWriteAPI ? this.writeBaseURL : this.readBaseURL
    const url = `${baseURL}${endpoint}`
    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
      ...options.headers as Record<string, string>
    }

    if (this.token) {
      headers['Authorization'] = `Bearer ${this.token}`
    }

    console.log('API请求:', {
      url,
      method: options.method || 'GET',
      headers,
      body: options.body,
      useWriteAPI
    })

    try {
      const response = await fetch(url, {
        ...options,
        headers
      })

      console.log('API响应状态:', response.status, response.statusText)

      if (!response.ok) {
        const errorText = await response.text()
        console.error('API错误响应:', errorText)
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const data = await response.json()
      console.log('API响应数据:', data)
      
      // 根据接口类型判断成功码
      // 登录接口成功码是100，MCI相关接口成功码可能是400或500，其他接口成功码是200
      let successCodes = [100, 200]
      
      // 如果是MCI相关接口，添加400和500作为成功码
      if (endpoint.includes('/MCI/')) {
        successCodes = [100, 200, 400, 500]
      }
      
      if (!successCodes.includes(data.code)) {
        throw new Error(data.message || '请求失败')
      }

      return data
    } catch (error) {
      console.error(`API请求失败 [${endpoint}]:`, error)
      throw error
    }
  }

  // 用户相关接口
  async login(data: LoginRequest): Promise<ApiResponse<LoginResponse>> {
    return this.request<LoginResponse>('/api/BaseData/Login', {
      method: 'POST',
      body: JSON.stringify(data)
    })
  }

  // 门诊费用相关接口
  async getVisitRecords(patientId: number): Promise<ApiResponse<VisitRecord[]>> {
    return this.request<VisitRecord[]>(`/api/MCI/VisitrecordQuery?PatientId=${patientId}`)
  }

  async getPrescriptionMedicines(visitrecordId: number): Promise<ApiResponse<PrescriptionMedicine[]>> {
    return this.request<PrescriptionMedicine[]>(`/api/MCI/PrescriptionMedicineQuery?VisitrecordId=${visitrecordId}`)
  }

  async getNotificationCount(): Promise<ApiResponse<{ count: number; unreadList: any[] }>> {
    return this.request('/api/user/notifications/count')
  }

  // 公告通知接口
  async getNotices(type?: string, page: number = 1, size: number = 10): Promise<ApiResponse<{ list: Notice[]; total: number; page: number; size: number }>> {
    const params = new URLSearchParams({
      page: page.toString(),
      size: size.toString()
    })
    if (type) params.append('type', type)
    
    return this.request(`/api/notices/suspension?${params.toString()}`)
  }

  // 服务相关接口
  async getServices(category?: string): Promise<ApiResponse<{ mainServices: Service[]; gridServices: Service[] }>> {
    const params = category ? `?category=${category}` : ''
    return this.request(`/api/services/list${params}`)
  }

  // 预约挂号接口
  async getAppointmentDepartments(date?: string): Promise<ApiResponse<{ list: any[] }>> {
    const params = date ? `?date=${date}` : ''
    return this.request(`/api/appointments/departments${params}`)
  }

  async createAppointment(data: {
    departmentId: number
    doctorId: number
    appointmentDate: string
    timeSlot: string
    patientId: number
    symptoms: string
    phone: string
  }): Promise<ApiResponse<{ appointmentId: string; appointmentNo: string; status: string; appointmentTime: string }>> {
    return this.request('/api/appointments/register', {
      method: 'POST',
      body: JSON.stringify(data)
    })
  }

  async getAppointmentRecords(status?: string, page: number = 1, size: number = 10): Promise<ApiResponse<{ list: Appointment[]; total: number; page: number; size: number }>> {
    const params = new URLSearchParams({
      page: page.toString(),
      size: size.toString()
    })
    if (status) params.append('status', status)
    
    return this.request(`/api/appointments/records?${params.toString()}`)
  }

  // 充值相关接口
  async getMedicalCardBalance(): Promise<ApiResponse<{ cardNo: string; balance: number; frozenAmount: number; availableAmount: number; lastRechargeTime: string }>> {
    return this.request('/api/user/medical-card/balance')
  }

  async createRechargeOrder(data: {
    amount: number
    paymentMethod: string
    cardNo: string
  }): Promise<ApiResponse<{ orderId: string; amount: number; paymentUrl: string; expireTime: string }>> {
    return this.request('/api/user/medical-card/recharge', {
      method: 'POST',
      body: JSON.stringify(data)
    })
  }

  async getRechargeHistory(page: number = 1, size: number = 10): Promise<ApiResponse<{ list: RechargeRecord[]; total: number; page: number; size: number }>> {
    const params = new URLSearchParams({
      page: page.toString(),
      size: size.toString()
    })
    
    return this.request(`/api/user/medical-card/recharge-history?${params.toString()}`)
  }

  // 缴费相关接口
  async getOutstandingBills(): Promise<ApiResponse<{ list: any[]; totalAmount: number }>> {
    return this.request('/api/payments/outstanding')
  }

    // 获取待缴费项目列表
  async getPaymentItems(patientId?: number): Promise<ApiResponse<any[]>> {
    const params = patientId ? `?PatientId=${patientId}` : ''
    return this.request(`/api/BaseData/AmountFTCommand${params}`)
  }

  async createPaymentOrder(data: {
    billIds: number[]
    paymentMethod: string
    amount: number
  }): Promise<ApiResponse<{ orderId: string; amount: number; paymentUrl: string; expireTime: string }>> {
    return this.request('/api/payments/pay', {
      method: 'POST',
      body: JSON.stringify(data)
    })
  }

  async getPaymentRecords(type?: string, page: number = 1, size: number = 10): Promise<ApiResponse<{ list: PaymentRecord[]; total: number; page: number; size: number }>> {
    const params = new URLSearchParams({
      page: page.toString(),
      size: size.toString()
    })
    if (type) params.append('type', type)
    
    return this.request(`/api/payments/records?${params.toString()}`)
  }

  // 就诊人管理接口
  async getPatients(): Promise<ApiResponse<Patient[]>> {
    return this.request<Patient[]>('/api/MCI/PatientQuery')
  }

  async getPatientById(patientId: number): Promise<ApiResponse<Patient>> {
    return this.request<Patient>(`/api/MCI/PatientByIdQuery?PatientId=${patientId}`)
  }

  async addPatient(data: PatientForm): Promise<ApiResponse<any>> {
    return this.request('/api/MCI/AddPatient', {
      method: 'POST',
      body: JSON.stringify(data)
    }, true) // 使用写API
  }

  async updatePatient(patientId: number, data: PatientForm): Promise<ApiResponse<any>> {
    return this.request('/api/MCI/UpdPatient', {
      method: 'POST',
      body: JSON.stringify({
        patientId,
        ...data
      })
    }, true) // 使用写API
  }

  async deletePatient(patientId: number): Promise<ApiResponse<any>> {
    return this.request(`/api/MCI/DelPatient?PatientId=${patientId}`, {
      method: 'DELETE'
    }, true) // 使用写API
  }

  // 住院人管理接口
  async getInpatients(): Promise<ApiResponse<{ list: Inpatient[] }>> {
    return this.request('/api/inpatients')
  }

  // 报告查询接口
  async getMedicalReports(type?: string, page: number = 1, size: number = 10): Promise<ApiResponse<{ list: MedicalReport[]; total: number; page: number; size: number }>> {
    const params = new URLSearchParams({
      page: page.toString(),
      size: size.toString()
    })
    if (type) params.append('type', type)
    
    return this.request(`/api/reports/medical?${params.toString()}`)
  }

  async getMedicalReportDetail(reportId: number): Promise<ApiResponse<any>> {
    return this.request(`/api/reports/medical/${reportId}`)
  }

  // 问题反馈接口
  async submitFeedback(data: {
    type: string
    title: string
    content: string
    contact: string
    images?: string[]
  }): Promise<ApiResponse<{ feedbackId: string; status: string; estimatedReplyTime: string }>> {
    return this.request('/api/feedback', {
      method: 'POST',
      body: JSON.stringify(data)
    })
  }

  // 候诊查询接口
  async getWaitingQueueStatus(departmentId?: number, doctorId?: number): Promise<ApiResponse<any>> {
    const params = new URLSearchParams()
    if (departmentId) params.append('departmentId', departmentId.toString())
    if (doctorId) params.append('doctorId', doctorId.toString())
    
    return this.request(`/api/waiting-queue/status?${params.toString()}`)
  }

  // 核酸检测接口
  async getNucleicAcidTestResults(): Promise<ApiResponse<any>> {
    return this.request('/api/tests/nucleic-acid/results')
  }

  async bookNucleicAcidTest(data: any): Promise<ApiResponse<any>> {
    return this.request('/api/tests/nucleic-acid/book', {
      method: 'POST',
      body: JSON.stringify(data)
    })
  }

  // 体检服务接口
  async getPhysicalExamPackages(): Promise<ApiResponse<any>> {
    return this.request('/api/physical-exams/packages')
  }

  async bookPhysicalExam(data: any): Promise<ApiResponse<any>> {
    return this.request('/api/physical-exams/book', {
      method: 'POST',
      body: JSON.stringify(data)
    })
  }

  async getPhysicalExamResults(): Promise<ApiResponse<any>> {
    return this.request('/api/physical-exams/results')
  }

  // 电子发票接口
  async getElectronicInvoices(): Promise<ApiResponse<any>> {
    return this.request('/api/invoices/electronic')
  }

  async downloadElectronicInvoice(invoiceId: string): Promise<ApiResponse<any>> {
    return this.request(`/api/invoices/electronic/${invoiceId}/download`)
  }

  // 退款相关接口
  async getRefundEligibleItems(): Promise<ApiResponse<any>> {
    return this.request('/api/refunds/eligible')
  }

  async requestRefund(data: any): Promise<ApiResponse<any>> {
    return this.request('/api/refunds/request', {
      method: 'POST',
      body: JSON.stringify(data)
    })
  }

  // 复诊配药接口
  async getRepeatPrescriptions(): Promise<ApiResponse<any>> {
    return this.request('/api/prescriptions/repeat-eligible')
  }

  async orderRepeatPrescription(data: any): Promise<ApiResponse<any>> {
    return this.request('/api/prescriptions/order-repeat', {
      method: 'POST',
      body: JSON.stringify(data)
    })
  }

  // 预约挂号记录相关接口
  async getAppointmentRecordsByPatient(patientId: number): Promise<ApiResponse<AppointmentRecord[]>> {
    return this.request<AppointmentRecord[]>(`/api/MCI/AppointmentByPatientQuery?PatientId=${patientId}`)
  }

  async getAppointmentRecordById(appointmentId: number): Promise<ApiResponse<AppointmentRecord>> {
    return this.request<AppointmentRecord>(`/api/MCI/AppointmentByIdQuery?AppointmentId=${appointmentId}`)
  }

  // 科室管理接口
  async getDepartments(): Promise<ApiResponse<any[]>> {
    return this.request<any[]>('/api/Manage/Handle')
  }

  // 预约添加接口
  async addAppointment(data: {
    appointmentId: number
    attending: string
    doctorAddress: string
    department: string
    attendingName: string
    doctorName: string
    registTypeId: number
    outpatientTime: string
    waitingTime: string
    cost: number
    appointmentTime: string
    medicalState: boolean
    reason: string
    cancelTime: string
    desc: string
    patientId: number
    departmentId: number
  }): Promise<ApiResponse<any>> {
    // 格式化时间字段
    const formattedData = {
      ...data,
      outpatientTime: data.outpatientTime ? new Date(data.outpatientTime).toISOString() : '',
      appointmentTime: data.appointmentTime ? new Date(data.appointmentTime).toISOString() : '',
      waitingTime: data.waitingTime ? 
        (data.waitingTime.includes('T') ? 
          new Date(data.waitingTime).toISOString() : 
          new Date(`2024-01-01T${data.waitingTime}`).toISOString()) : 
        new Date().toISOString(),
      cancelTime: data.cancelTime || new Date().toISOString()
    }

    return this.request('/api/Appoint/AddAppoint', {
      method: 'POST',
      body: JSON.stringify({ 
        add: formattedData,
        appointments: formattedData 
      })
    }, true) // 使用写API
  }

  // 预约须知查询接口
  async getAppointmentNotice(): Promise<ApiResponse<{
    noticeId: number
    noticeName: string
    dateTime: string
  }>> {
    return this.request('/api/MCI/NoticeQueryFirst')
  }
}

// 创建API实例
export const api = new SmartYLAPI('', '')

// 导出API类供其他地方使用
export default SmartYLAPI

